<template>
  <div class="app-container-box">
    <div class="box-tag" />
    <div class="title-text-box">
      <span class="title-text">观看授权</span>
      <span class="title-tips-text">注：观众白名单内的观众通过观众名和密码才能观看直播，导入将增量上传新名单，若想完全替换名单，请先清空名单后重新上传可分批导入，每个渠道最多可导入1万条，每个频道总量最多可导入10万条</span>
    </div>
    <div class="warp-line-top" />

    <div class="auth-method-box">
      <span class="auth-method-text">当前授权方式：</span>
      <el-radio-group v-model="currentAuthMethod">
        <el-radio label="Public" @click="updateLiveReq">无限制</el-radio>
        <el-radio label="Private" @click="updateLiveReq">观众白名单</el-radio>
      </el-radio-group>

      <download-excel
        v-if="currentAuthMethod === 'Private'"
        class="downloadExcel"
        :data="excel_data"
        :fields="json_fields"
        worksheet="sheet1"
        name="用户授权导入模板.xls"
      >
        <el-button type="text">下载excel模板</el-button>
      </download-excel>
    </div>

    <div class="warp-line-middle" />

    <div v-if="currentAuthMethod === 'Private'">
      <div class="middle-btns-box">
        <el-form>
          <el-form-item
            class="opt"
            prop="password"
          >
            <el-input
              v-model="livePassword"
              prefix-icon="el-icon-lock"
              placeholder="设置频道密码"
              :type="flag?'text':'password'"
              :disabled="isDisablePasswordInput"
            >
              <i
                slot="suffix"
                :class="[flag?'el-icon-minus':'el-icon-view']"
                style="margin-top:8px;font-size:18px;"
                autocomplete="auto"
                @click="flag=!flag"
              />
            </el-input>
          </el-form-item>
        </el-form>
        <el-checkbox v-model="isEnablePassword" @change="passwordCheckboxChanged">开启密码验证</el-checkbox>
        <input ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx, .xls" @change="handleClick">
        <el-button :loading="uploadExcelLoading" type="primary" style="margin-left: 10px" @click="handleUpload">导入白名单</el-button>
        <el-button type="danger" @click="deleteUserListVisible = true">清空</el-button>
        <el-button type="primary" @click="saveChangeBtn">保存</el-button>
        <el-pagination
          small
          layout="total, prev, pager, next, jumper"
          :total="totalUserList"
          :page-size="whiteUserQuery.length"
          :pager-count="pagerCount"
          @current-change="onPageChanged"
        />
        <el-dialog
          title="提示"
          :visible.sync="deleteUserListVisible"
          width="30%"
        >
          <span>是否清空用户列表？</span>
          <span slot="footer" class="dialog-footer">
            <el-button @click="deleteUserListVisible = false">取消</el-button>
            <el-button type="primary" @click="handleDeleteUserList">确定</el-button>
          </span>
        </el-dialog>

      </div>

      <div class="table-list-box">
        <el-table
          :data="whiteUserData"
          style="width: 100%"
          :header-cell-style="elTableHeaderStyle"
          :cell-style="elTableCellStyle"
        >
          <el-table-column
            prop="id"
            label="用户ID"
            align="center"
          />
          <el-table-column
            prop="name"
            label="姓名"
            align="center"
          />
          <el-table-column
            prop="hospital"
            label="单位(医院)"
            align="center"
          />
          <el-table-column
            prop="department"
            label="部门(科室)"
            align="center"
          />
          <el-table-column
            prop="phone"
            label="电话"
            align="center"
          />
          <el-table-column
            align="right"
          >
            <template slot="header" slot-scope="scope">
              <el-input
                v-model="keyword"
                size="mini"
                placeholder="输入关键字搜索"
                @click="scope"
              />
            </template>
            <!-- <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
              >Delete</el-button>
            </template> -->
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  updateLive,
  batchDeletetLiveUsers,
  batchInsertLiveUsers,
  batchListLiveUsers
} from '@/api/lives'
import { Base64 } from 'js-base64'
import Vue from 'vue'
import JsonExcel from 'vue-json-excel'
import XLSX from 'xlsx'
Vue.component('downloadExcel', JsonExcel)

export default {

  components: {
  },
  data() {
    return {
      keyword: '',
      pagerCount: 5,
      deleteUserListVisible: false,
      // 非公开的直播类型
      privateTypes: ['WhiteListAndPassword', 'WhiteList', 'Password', 'Private'],
      totalUserList: 0,
      excelData: {
        header: null,
        results: null
      },
      tableData: [],
      tableHeader: [],
      // 上传excel等待状态
      uploadExcelLoading: false,
      isEnablePassword: false,
      isDisablePasswordInput: true,
      json_meta: [
        [
          {
            key: 'charset',
            value: 'utf-8'
          }
        ]
      ],
      fileUploadHeaders: {
        Authorization: ''
      },
      livePassword: '',
      flag: false,
      // 默认认证类型
      currentAuthMethod: 'Public',
      whiteUserData: [],
      whiteUserQuery: {
        start: 1,
        length: 10,
        keyword: ''
      },
      updateLiveData: {
        LivePassword: '',
        AuthType: ''
      },
      json_fields: {
        '用户ID': 'user_id',
        '姓名': 'name',
        '单位(医院)': 'hospital',
        '部门(科室)': 'department',
        '电话': 'phone'
      },
      excel_data: [
        {
          user_id: 'user_id',
          name: 'name',
          hospital: 'hospital',
          department: 'department',
          phone: 'phone'
        }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'choicedLive',
      'token'
    ])
  },
  watch: {
    'choicedLive'(n, o) {
      if (n.LivePassword) {
        this.livePassword = Base64.decode(n.LivePassword)
      }
      if (['WhiteListAndPassword', 'Password'].includes(n.AuthType)) {
        this.isEnablePassword = true
      } else {
        this.isEnablePassword = false
        this.livePassword = ''
      }
      this.refreshwhiteUserData()
    },
    'token'(n, o) {
      this.fileUploadHeaders.Authorization = n
    },
    currentAuthMethod: {
      async handler(n, o) {
        if (n === 'Private') {
          this.refreshwhiteUserData()
        } else {
          console.log('11111111111111111111111111111111')
          this.updateLiveData.AuthType = 'Public'
          this.updateLiveReq()
        }
      }
    },
    livePassword: {
      async handler(n, o) {
        this.updateLiveData.LivePassword = Base64.encode(n)
      }
    },
    keyword: {
      async handler(n, o) {
        this.whiteUserQuery.keyword = n
      }
    },
    isEnablePassword: {
      async handler(n, o) {
        if (n === true) {
          this.isDisablePasswordInput = false
        } else {
          this.isDisablePasswordInput = true
          this.livePassword = ''
        }
      }
    },
    whiteUserQuery: {
      async handler(n, o) {
        batchListLiveUsers(this.whiteUserQuery, this.choicedLive.id).then((res) => {
          this.whiteUserData = res.data
          this.totalUserList = res.count
        })
      },
      deep: true
    }
  },
  async mounted() {
    // 设置访问头
    this.fileUploadHeaders.Authorization = this.token
    if (this.privateTypes.includes(this.choicedLive.AuthType)) {
      this.currentAuthMethod = 'Private'
      // 刷新白名单列表
    }
    // 密码
    if (this.choicedLive.LivePassword && ['WhiteListAndPassword', 'Password'].includes(this.choicedLive.AuthType)) {
      this.livePassword = Base64.decode(this.choicedLive.LivePassword)
      this.isEnablePassword = true
    }
  },
  methods: {
    handleDeleteUserList() {
      this.deleteWhiteUserList()
      this.deleteUserListVisible = false
    },
    // 分页变化时
    onPageChanged(ev) {
      this.whiteUserQuery.start = ev
    },
    // 更新直播
    updateLiveReq() {
      updateLive(this.updateLiveData, this.choicedLive.id).then((res) => {
        if (res.code === 200) {
          this.$message({
            message: '修改成功',
            type: 'success'
          })
        }
      })
    },
    saveChangeBtn() {
      this.changeUpdateData()
      this.updateLiveReq()
    },
    changeUpdateData() {
      // 设置类型
      // 仅密码
      if (this.livePassword.length > 0 && this.whiteUserData.length <= 0) {
        this.updateLiveData.AuthType = 'Password'
        // 仅白名单
      } else if (this.livePassword.length <= 0 || !this.livePassword) {
        this.updateLiveData.AuthType = 'WhiteList'
        // 白名单+密码
      } else if (this.livePassword.length > 0 && this.whiteUserData.length > 0) {
        this.updateLiveData.AuthType = 'WhiteListAndPassword'
      }
    },
    async refreshwhiteUserData() {
      if (this.choicedLive.id) {
        var live_id = this.choicedLive.id
        this.whiteUserQuery.start = 1
        var res = await batchListLiveUsers(this.whiteUserQuery, live_id)
        this.whiteUserData = res.data
        this.totalUserList = res.count
        if (this.privateTypes.includes(this.choicedLive.AuthType)) {
          this.currentAuthMethod = 'Private'
        }
        this.changeUpdateData()
        if (this.choicedLive.LivePassword && this.choicedLive.LivePassword.length > 0) {
          this.LivePassword = Base64.decode(this.choicedLive.LivePassword)
        }
      }
    },
    elTableHeaderStyle() {
      return {
        background: '#F0F1F2',
        font_size: '18px',
        font_family: 'PingFang SC',
        font_weight: 400,
        color: '#6D7A8E'
      }
    },
    elTableCellStyle() {
      return {
        font_size: '20px',
        font_family: 'PingFang SC',
        font_weight: 400,
        color: '#8B9DBA'
      }
    },
    clickChangeAuthType() {
      this.$router.push({ path: '/permission/changetype', query: '' }).catch()
    },
    generateData({ header, results }) {
      this.excelData.header = header
      this.excelData.results = results
      this.onSuccess && this.onSuccess(this.excelData)
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      this.$refs['excel-upload-input'].click()
    },
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      if (!rawFile) return
      this.upload(rawFile)
    },
    upload(rawFile) {
      this.$refs['excel-upload-input'].value = null // fix can't select the same excel

      if (!this.beforeUpload) {
        this.readerData(rawFile)
        return
      }
      const before = this.beforeUpload(rawFile)
      if (before) {
        this.readerData(rawFile)
      }
    },
    readerData(rawFile) {
      this.uploadExcelLoading = true
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = e => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          worksheet['!ref'] = worksheet['!ref'].replace('A1', 'A2') // 忽略第1行中文字段说明
          const results = XLSX.utils.sheet_to_json(worksheet)
          this.generateData({ header, results })
          this.uploadExcelLoading = false
          resolve()
        }
        reader.readAsArrayBuffer(rawFile)
      })
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r + 1 // 忽略第一行表头
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) { /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C// <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    isExcel(file) {
      return /\.(xlsx|xls|csv)$/.test(file.name)
    },
    // 上传excel后处理
    async onSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      // 批量导入白名单用户
      var res = await batchInsertLiveUsers(results, this.choicedLive.id)
      if (res.code !== 200) {
        this.$message.error('导入失败')
        return
      }
      this.changeUpdateData()
      // 刷新数据
      await this.refreshwhiteUserData()
      // 更新数据
      await this.updateLiveReq()
    },
    // 上传excel前处理
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 20

      if (isLt1M) {
        return true
      }

      this.$message({
        message: '文件大小不能超过20Mb',
        type: 'warning'
      })
      return false
    },
    // 清空白名单
    async deleteWhiteUserList() {
      var res = await batchDeletetLiveUsers(this.choicedLive.id)
      if (res.code === 200) {
        this.$message({
          message: '清空成功！',
          type: 'success'
        })
      }
      this.changeUpdateData()
      // 刷新数据
      await this.refreshwhiteUserData()
      // 更新直播
      await this.updateLiveReq()
    },
    // 密码复选框变化
    passwordCheckboxChanged(ev) {
      if (ev) {
        this.isDisablePasswordInput = false
      } else {
        this.isDisablePasswordInput = true
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container-box {
  height: 1010px;

}
.box-tag {
  width: 4px;
  height: 28px;
  background: #2E9BEA;
  border-radius: 2px;
  position: relative;
  top: 25px;
}

.warp-line-top {
  width: 1627px;
  height: 4px;
  background: #EDF5FB;
  top: 85px;
  position: absolute;
}
.title-box {
    width: 1423px;
    height: 79px;
    border: 1px solid #9CABC3;
    border-radius: 3px;
    display: flex;
    align-items: center;
    position: absolute;
    top: 98px;
    left: 55px;
    .auth-method-text {
        width: auto;
        height: 18px;
        font-size: 18px;
        font-family: PingFang SC;
        font-weight: 400;
        color: #6D7A8E;
        left: 28px;
        position: absolute;
    }
}
.table-list-box {
  position: absolute;
  top: 245px;
  left: 55px;
  width: 1518px;
  height: 654px;
}
.title-text-box {
  display: inline-flex;
  flex-wrap: nowrap;
  align-items: center;
  .title-tips-text {
    width: auto;
    height: 13px;
    font-size: 12px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #97A8C4;
    position: absolute;
    left: 173px;
  }
  .title-text{
    width: 171px;
    height: 23px;
    font-size: 24px;
    font-family: PingFang SC;
    font-weight: 400;
    color: #4A5462;
    top: 31px;
    left: 54px;
    position: absolute;
}
}
.warp-line-middle {
  width: 1627px;
  height: 4px;
  background: #EDF5FB;
  position: absolute;
  top: 171px;
}
.auth-method-box {
        width: 100%;
        height: auto;
        border-radius: 3px;
        display: flex;
        align-items: center;
        position: absolute;
        top: 129px;
        left: 48px;
        span {
            width: auto;
            height: 18px;
            font-size: 18px;
            font-family: PingFang SC;
            font-weight: 400;
            color: #6D7A8E;
        }
    }

.middle-btns-box{
  width: 60%;
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  position: absolute;
  top: 197px;
  right: 0px;
  .el-input {
    width: 227px;
    // border: 1px solid #AFBDD2;
    border-radius: 3px;
  }
  ::v-deep {
    .el-form-item {
      margin-bottom: 0px;
      margin-right: 5px;
    }
  }
}
.excel-upload-input{
  display: none;
  z-index: -9999;
}
.downloadExcel {
  margin-right: 10px;
  margin-left: 10px;
  position: absolute;
  right: 100px;
}
</style>
